// stores/user.js
import { defineStore } from 'pinia';
import { getTrStrategyList } from "/api/TrStrategy";

export const useStrategyStore = defineStore('strategy', {
  state: () => ({
    list: [],
    pageNum: 1,
    pageSize: 30,
    pageCount: 0,
    total: 0,
    provinceId: null,
    tagId: null,
    keywords: null,
    loading: false,
    loaded: false
  }),
  actions: {
    // 获取列表
    async getList({ provinceId = null, tagId = null, keywords = null, pageNum = 1 } = {}) {
      if (this.loading) return;
      if (
        (provinceId == this.provinceId)
        && (tagId == this.tagId)
        && (keywords == this.keywords)
        && (pageNum == this.pageNum)
        && this.loaded
      ) return;
      this.loading = true;
      this.loaded = this.loaded|| true;
      this.provinceId = provinceId;
      this.tagId = tagId;
      this.keywords = keywords;
      this.pageNum = pageNum;
      const data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      if (this.provinceId) {
        data['provinceId'] = this.provinceId
      }
      if (this.tagId) {
        data['tagId'] = this.tagId
      }
      if (this.keywords) {
        data['keywords'] = this.keywords
      }

      try {
        const { code, rows, total } = await getTrStrategyList(data);
        this.loading = false;
        if (code === 200) {
          this.list = rows;
          this.total = total;
          this.pageCount = Math.ceil(total / this.pageSize);
        } else {
          console.error(`Failed to fetch list: code ${code}`);
        }
      } catch (error) {
        console.error('Error fetching list:', error);
      }
    },

    // 获取下一页
    async getNextPage() {
      if (this.pageNum < this.pageCount) {
        await this.getList({ pageNum: this.pageNum + 1 });
      } else {
        console.info('No more pages to load');
      }
    },

    // 获取下一页
    async changePrivace({ provinceId = null, pageNum = 1 } = {}) {
      await this.getList({ 
        pageNum, 
        provinceId:provinceId || null,
        tagId: this.tagId }
      );
    },
  },
});
